#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import time
import jwt

#  pip3 install pyjwt

JWT_TOKEN_EXPIRE_TIME = 3600 * 24  # token有效时间 24小时
JWT_SECRET = 'woshimiaojie'  # 加解密密钥
JWT_ALGORITHM = 'HS256'  # 加解密算法


def generate_jwt_token(id: int, mobile: int, email: str, userName: str) -> str:
    """
        @summary: 根据参数生成token
        @param id:用户id,必填,int类型,并将条件值传递进来
        @param mobile:手机号,必填,int类型,并将条件值传递进来
        @param email:邮箱,必填,str类型,并将条件值传递进来
        @param userName:姓名,必填,str类型,并将条件值传递进来
        @return: 返回token str类型
    """
    payload = {'id': id, 'mobile': mobile, 'email': email, 'userName': userName, 'exp': int(time.time()) + JWT_TOKEN_EXPIRE_TIME}
    token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
    return token


def verify_jwt_token(token: str) -> bool:
    """验证用户token"""

    try:
        _payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
    except jwt.PyJWTError:
        print('token解析失败')
        return False
    else:
        print(_payload)
        exp = int(_payload.pop('exp'))
        if time.time() > exp:
            print('已失效')
            return False
        return _payload

if __name__ == '__main__':
    user_id = 123
    token = generate_jwt_token(user_id)
    # token = generate_jwt_token(user_id,mobile=17339809807,email='miaojie@otosaas.com',userName='苗杰')
    print(token)
    print(verify_jwt_token(user_id, token))
